package com.hanxu.controller;

import com.hanxu.pojo.Books;
import com.hanxu.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.awt.print.Book;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    /**
     *@AutoWired自动装配默认是按类型匹配的，当且仅有一个匹配的Bean时，spring将其注入到@AutoWired标注的变量中
     * //controller 调用 server层
     *@Qualifier(指定注入Bean的名称)   注意这里要在BookServerImpl.java中加入@Component("BookServiceImpl") 不然无法找到bean`
     */
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    /**
     * 显示所有书籍功能
     * @param model
     * @return
     */
    @RequestMapping("/allBook")
    public String list(Model model){
        List<Books> list = bookService.queryAllBook();
        model.addAttribute("list",list);

        return "allbook";
    }

    /**
     * 跳转到书籍增加界面
     * @return
     */
    @RequestMapping("/toAddBook")
    public String toAddBook(){
        return "toAddBook";
    }

    /**
     * 添加一本书
     * @param books
     * @return
     */
    @RequestMapping("/addBook")
    public String addBook(Books books){
        System.out.println(books);
        bookService.addBook(books);
        return "redirect:/book/allBook";
    }

    /**
     * 跳转到修改页面
     * http://localhost:8080/book/updateBook?id=1
     * id会自动传递过来
     * @return
     */
    @RequestMapping("/toupdateBook")
    public String toupdateBook(int id,Model model){
        Books books = bookService.queryBookById(id);
        model.addAttribute("books",books);
        return "toupdateBook";
    }

    /**
     * 修改 需要提交事务 我们使用aop的横切方式
     * @param books
     * @return
     */
    @RequestMapping("/updatebook")
    public String updateBook(Books books){
        int i = bookService.updateBook(books);
        return "redirect:/book/allBook";
    }


    /**
     * restful 风格传递参数
     * 删除书籍
     * @param id
     * @return
     */
    @RequestMapping("/deleteBook/{bookid}")
    public String deleteBook(@PathVariable("bookid") int id){
        int i = bookService.deleteById(id);
        System.out.println(i);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/queryByName/{bookName}")
    public String queryByName(@PathVariable("bookName") String bookName,Model model){
        System.out.println("bookName======================="+bookName);
        List<Books> list = bookService.queryBookByName("%"+bookName+"%");
        System.out.println("list==++++++++=="+list);
        model.addAttribute("list",list);
        return "allBook";
    }

}
